#!groovy

@NonCPS
def findBuildByTagName(String jobName, String tagName) {
  return Jenkins.instance.getItem('sync_release').getItem(jobName).builds
    .findAll {
        it ->
        it.result.equals(Result.SUCCESS) &&
        it.getAction(hudson.plugins.git.util.BuildData.class)
          .lastBuild
          .revision
          .containsBranchName("refs/tags/${tagName}")
    }.collect {
        it -> it.number
    }.find { true }
}

@NonCPS
def findValueInDepFile(String depFile, String key) {
    def value = depFile.readLines().find {
        it -> it.startsWith("${key}=")
    }
    if (!value) {
        throw new IllegalStateException("Key ${key} not found in dependencies file")
    }
    return value.split('=')[1]
}

def buildComponent(String target, String archive) {
    withEnv([
            "REALM_CORE_VERSION=current",
            "REALM_SWIFT_VERSION=2.3"
    ]) {
        sh """
            sh tightdb_objc/build.sh ${target}
            mv ${archive} ./
            rm -rf tightdb_objc/build
        """
    }
}

def getVersionPublish(String version) {
    dir('realm-cocoa') {
        sh "git describe --exact-match --tags HEAD > tags.txt 2>&1 || true"
        def tag = readFile('tags.txt').readLines().last().trim()
        echo "Read tag ${tag}"
        if (tag.contains(" no tag exactly matches")) {
            sh "git rev-parse HEAD | cut -b1-8 > sha.txt "
            def sha = readFile('sha.txt').readLines().last().trim()
             echo "Read sha ${sha}"
            return version + "-" + sha
        }
        if (!tag.equals("v${version}".toString())){
          currentBuild.rawBuild.setResult(Result.FAILURE)
          throw new Exception("Version v${version} != ${tag}")
        }
        return version
    }
}

def uploadToS3(List<String> files, String publishVersionNumber){
    for (String file in files)  {
        sh "/usr/local/bin/s3cmd put ${file} 's3://realm-ci-artifacts/cocoa-framework/${publishVersionNumber}/'"
    }
    echo "Uploaded files to 's3://realm-ci-artifacts/cocoa-framework/${publishVersionNumber}/'"
}

def archiveFiles(List<String> files){
    for (String file in files)  {
        archive "${file}"
    }
}

def publish(List<String> files, publishVersionNumber) {
    if (UPLOAD_TO_S3 == 'true') {
        uploadToS3(files, publishVersionNumber)
    }
    else {
        archiveFiles(files)
    }
}

def repackArchives(String objcArchiveName, String swiftArchiveName, String osxArchiveName, String swiftOsxArchiveName) {
    dir('realm-objc') {
        sh 'rm -rf *'
        dir('osx') {
            sh 'unzip ../../realm-framework-osx.zip'
        }
        dir('ios') {
            dir('static') {
                sh 'unzip ../../../realm-framework-ios.zip'
            }
            dir('dynamic') {
                sh 'unzip ../../../realm-dynamic-framework-ios.zip'
            }
        }
        dir('tvos') {
            sh 'unzip ../../realm-framework-tvos.zip'
        }

        sh 'zip --symlinks -r -q ../realm-objc.zip ios osx tvos'
    }
    dir('realm-swift') {
        sh 'rm -rf *'
        dir('osx') {
            sh ' unzip ../../realm-swift-framework-osx.zip'
        }
        dir ('ios') {
            sh ' unzip ../../realm-swift-framework-ios.zip'
        }
        dir('tvos') {
            sh 'unzip ../../realm-swift-framework-tvos.zip'
        }

        sh 'zip --symlinks -r -q ../realm-swift.zip ios osx tvos'
    }
    sh """
        mv realm-objc.zip ${objcArchiveName}
        mv realm-swift.zip ${swiftArchiveName}
        mv realm-framework-osx.zip ${osxArchiveName}
        mv realm-swift-framework-osx.zip ${swiftOsxArchiveName}
    """
}

node('osx') {
    stage 'SCM'
    dir('realm-cocoa') {
        sshagent(['realm-ci-ssh']) {
            checkout([
                  $class: 'GitSCM',
                  branches: [[name: GIT_REF]],
                  browser: [$class: 'GithubWeb',
                  repoUrl: 'https://github.com/realm/realm-cocoa'],
                  extensions: [
                    [$class: 'SubmoduleOption', disableSubmodules: false, recursiveSubmodules: true, reference: '', trackingSubmodules: false],
                    [$class: 'CleanCheckout']],
                  gitTool: 'native git',
                  userRemoteConfigs: [[
                    credentialsId: '3e71241e-8920-4ecc-884b-418eb92b81ea',
                    name: 'origin',
                    refspec: '+refs/tags/*:refs/remotes/origin/tags/* +refs/heads/*:refs/remotes/origin/*',
                    url: 'https://github.com/realm/realm-cocoa.git'
                  ]]
            ])
        }
    }

    def depFile = readFile('realm-cocoa/dependencies.list')
    def syncVersionNumber = findValueInDepFile(depFile, 'REALM_SYNC_VERSION')
    def currentVersionNumber = findValueInDepFile(depFile, 'VERSION')
    def publishVersionNumber = getVersionPublish(currentVersionNumber)

    def objcArchiveName = "realm-objc_${currentVersionNumber}-sync-${syncVersionNumber}.zip"
    def swiftArchiveName = "realm-swift_${currentVersionNumber}-sync-${syncVersionNumber}.zip"
    def osxArchiveName = "realm-framework-osx_${currentVersionNumber}-sync-${syncVersionNumber}.zip"
    def swiftOsxArchiveName = "realm-swift-framework-osx_${currentVersionNumber}-sync-${syncVersionNumber}.zip"

    echo "Sync version: ${syncVersionNumber}"
    sh 'rm -rf realm-*.zip'

    dir('temp') {
        sh 'rm -rf *'
        sh "/usr/local/bin/s3cmd get --recursive 's3://realm-ci-artifacts/sync/${syncVersionNumber}/cocoa/'"
        sh 'tar xf realm-sync-cocoa-1.*.tar.xz'
    }

    sh 'ln -s "$(pwd)/temp/core" realm-cocoa/core'
    sh 'ln -s "$(pwd)/realm-cocoa" tightdb_objc'
    sh 'bash realm-cocoa/scripts/reset-simulators.sh'

    stage 'Build'
    buildComponent('package-ios-static', 'tightdb_objc/build/ios-static/realm-framework-ios.zip')
    buildComponent('package-ios-dynamic', 'tightdb_objc/build/ios/realm-dynamic-framework-ios.zip')
    buildComponent('package-ios-swift', 'tightdb_objc/build/ios/realm-swift-framework-ios.zip')
    buildComponent('package-osx', 'tightdb_objc/build/DerivedData/Realm/Build/Products/Release/realm-framework-osx.zip')
    buildComponent('package-osx-swift', 'tightdb_objc/build/osx/realm-swift-framework-osx.zip')
    buildComponent('package-tvos', 'tightdb_objc/build/tvos/realm-framework-tvos.zip')
    buildComponent('package-tvos-swift', 'tightdb_objc/build/tvos/realm-swift-framework-tvos.zip')

    stage 'Archive'
    repackArchives(objcArchiveName, swiftArchiveName, osxArchiveName, swiftOsxArchiveName)

    ArrayList<String> files = new ArrayList<String>()
    files.add(objcArchiveName)
    files.add(swiftArchiveName)
    files.add(osxArchiveName)
    files.add(swiftOsxArchiveName)

    publish(files, publishVersionNumber)
}
